//
//  MainViewController.swift
//  sinaWB
//
//  Created by 杨运旺 on 15/11/7.
//  Copyright © 2015年 杨运旺. All rights reserved.
//

import UIKit

class MainViewController: UITabBarController {
    
     // MARK: - 监听方法
    @objc private func clickComposedButton(){
        print("点我了")
    }
    
    
    // MARK: - 生命周期函数
    override func viewDidLoad() {
        super.viewDidLoad()

        addChildViewControllers()
        
        print(tabBar.subviews)
        
        setupComposedButton()
    }
    
    
    override func viewWillAppear(animated: Bool) {
        // 会创建 tabBar 中的所有控制器对应的按钮！
        super.viewWillAppear(animated)
        //将撰写按钮弄到最前面
        tabBar.bringSubviewToFront(composedButton)
    }
    
    // MARK: - 懒加载控件
    private lazy var composedButton: UIButton = UIButton(
        imgName: "tabbar_compose_icon_add",
        backImgName: "tabbar_compose_button")
}

// MARK: - 设置界面
extension MainViewController{
    
    
    /// 设置撰写按钮
    private func setupComposedButton(){
        // 添加按钮
        tabBar.addSubview(composedButton)
        // 调整按钮
        let count = childViewControllers.count
        
        let w = tabBar.bounds.width / CGFloat(count) - 1
        composedButton.frame = CGRectInset(tabBar.bounds, 2 * w, 0)
        
        
        composedButton .addTarget(self, action: "clickComposedButton", forControlEvents: .TouchUpInside)
    }
    
    ///添加所有控制器
    private func addChildViewControllers(){
       
        addChildViewController(HomeTableViewController(), title: "首页", imgName: "tabbar_home")
        addChildViewController(DiscoverTableViewController(), title: "消息", imgName: "tabbar_message_center")
        
        //占用一个位置
        addChildViewController(UIViewController())
        addChildViewController(MessageTableViewController(), title: "发现", imgName: "tabbar_discover")
        addChildViewController(ProfileTableViewController(), title: "我", imgName: "tabbar_profile")
    }
    
    
    /// 添加控制器
    private func addChildViewController(vc: UIViewController , title:String , imgName:String) {

        
        //设置标题
        vc.title = title
        
        //设置图像
        vc.tabBarItem.image = UIImage(named: imgName)
        
        //导航控制器
        let nav = UINavigationController(rootViewController: vc);
        //添加子控制器
        addChildViewController(nav)
    }
    
}
